<template>
  <div @click="filterChangeRef.gradeAndClassOpen = false">
    <!-- 表单查询 -->
    <div class="top">
      <TabList @onTabsValue="onTabsValue" />
      <Form
        ref="formRef"
        name="advanced_search"
        class="ant-advanced-search-form"
        style="margin-left: 24px"
        :model="formState"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <Row :gutter="[16, 1]">
          <Col :span="6">
            <Form.Item label="年级/班级" name="gradeId">
              <FilterChange ref="filterChangeRef" />
            </Form.Item>
          </Col>
          <Col :span="10">
            <Form.Item v-if="activeKey !== 'all'" label="检查时间">
              <a-range-picker
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
                :value="formState.createValue"
                :get-calendar-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                :allow-clear="true"
                @change="onRangeChange"
              />
            </Form.Item>
            <Form.Item v-else label="统计周期">
              <a-range-picker
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
                :value="formState.createValue"
                :get-calendar-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                :allow-clear="false"
                @change="onRangeChange"
              />
            </Form.Item>
          </Col>
        </Row>
        <div class="search">
          <div class="search-btn">
            <a-button type="primary" html-type="submit" @click="onSearch(1)">查询</a-button>
            <a-button ghost style="margin: 0 0 0 16px" @click="onReset">重置</a-button>
          </div>
        </div>
      </Form>
    </div>
    <!-- 列表 -->
    <div class="below">
      <div v-if="activeKey === 'all' && rankingState" class="ranking">
        <span class="ranking-text">排名</span>
        <CloseOutlined style="font-size: 20px; color: #c2c2c2; cursor: pointer" @click="close" />
      </div>
      <div class="search">
        <div></div>
        <div class="search-btn-right">
          <a-button
            v-if="activeKey === 'all' && rankingState && rankingOrder"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="asc"
          >
            <template #icon><SwapOutlined :style="{ transform: 'rotateZ(90deg)' }" /></template>
            正序
          </a-button>
          <a-button
            v-if="activeKey === 'all' && rankingState && !rankingOrder"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="desc"
          >
            <template #icon><SwapOutlined :style="{ transform: 'rotateZ(90deg)' }" /></template>
            反序
          </a-button>
          <a-button
            v-if="activeKey === 'all' && !rankingState"
            type="primary"
            style="margin-right: 16px; display: flex; align-items: center"
            html-type="submit"
            ghost
            @click="ranking()"
          >
            <template #icon><ToTopOutlined /></template>
            查看排行
          </a-button>
          <a-button
            :type="delStateClick"
            :ghost="isStudentLeadingOut"
            :loading="btnLoading"
            style="display: flex; align-items: center"
            @click="exports"
          >
            <template #icon><ToTopOutlined /></template>
            导出
          </a-button>
        </div>
      </div>
      <!-- 表格 -->
      <div>
        <a-table
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data-source="tableData.records"
          :row-key="record => record.indexId"
          :pagination="false"
          :loading="loading"
          :scroll="{ x: 1300 }"
        >
          <!-- <template v-slot:emptyText>{{ loading ? '' : '暂无数据' }}</template> -->
          <template v-slot:emptyText>
            <div class="zz-global-nodata">
              <img
                v-if="searchStatus * 1 === 0"
                src="@/assets/images/accommodation/default-no-data.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/no-data-search-new.png" alt="" />
            </div>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'roomVOList'">
              <div
                v-for="(item, index) in record.roomVOList"
                :key="index"
                style="
                  font-size: 14px;
                  color: #222222;
                  width: 170px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              >
                <Tooltip
                  :overlay-style="{ whiteSpace: 'normal' }"
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  placement="topLeft"
                  :title="item.dormitoryName + ' ' + item.roomName + ' ' + item.roomScore"
                >
                  <span>{{ item.dormitoryName }} {{ item.roomName }} {{ item.roomScore }}；</span>
                </Tooltip>
              </div>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button
                type="primary"
                size="small"
                ghost
                @click="onDeta(record, record.classId, record.className, record.gradeName)"
              >
                查看
              </a-button>
            </template>
          </template>
        </a-table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <span style="color: #999999; margin-right: 8px">共{{ tableData.pages }}页</span>
        <a-pagination
          v-model:current="tableData.current"
          v-model:pageSize="tableData.size"
          :page-size-options="pageSizeOptions"
          show-quick-jumper
          :total="tableData.total"
          :show-size-changer="true"
          @change="onChangePagination"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch, computed, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { Form, Row, Col, Message, Tooltip } from 'ant-design-vue';
import { gradeList, classList } from '@/api/common';
import { ToTopOutlined, CloseOutlined, SwapOutlined } from '@ant-design/icons-vue';
import TabList from '../components/tebPane/TabPane.vue';
import moment from 'moment';
import {
  getClassExamineCategory,
  getComplexExamineCategory,
  exportCollectiveExamine,
  exportItemExamine,
  exportCollectiveRanking
} from '@/api/assessment/classCollective';
import dayjs from 'dayjs';
import FilterChange from '@/components/filterChange/index.vue';
import { debounce } from '@/utils/debounce.js';
const router = useRouter();
const localStorageSchoolId = localStorage.getItem('localStorageSchoolId');
const schoolBaseId = ref(0);
const dayCreateValue = ref([]);
const searchStatus = ref(0);
const formState = ref({
  itemSuperiorId: 0, // 考核分类，0为综合查询 其余分类依照学校设置为准
  studentName: '', // 姓名
  releaseUserName: '',
  dormitoryId: '', // 宿舍楼
  sex: '', // 性别
  roomId: '', // 房间名称
  studentState: '', // 学生状态
  allocationStatus: '', // 分配状态
  examineStartTime: '', // 开始时间
  examineStopTime: '', // 结束时间
  createValue: dayCreateValue.value,
  current: 1,
  size: 10
});
onMounted(() => {
  let classCollectiveQuery = localStorage.getItem('classCollectiveQuery');
  dataForm();
  if (
    !classCollectiveQuery ||
    classCollectiveQuery === null ||
    classCollectiveQuery === undefined
  ) {
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
  }

  if (
    localStorageSchoolId === '346001568933441537' ||
    localStorageSchoolId === '221954838718582784'
  ) {
    schoolBaseId.value = 1;
  } else {
    schoolBaseId.value = 0;
  }
  obtainQuery();
});
function obtainQuery() {
  let classCollectiveQuery = localStorage.getItem('classCollectiveQuery');
  console.log('我cnim班级集体考核', classCollectiveQuery);
  if (classCollectiveQuery && classCollectiveQuery !== null) {
    let classCollectiveQueryJson = JSON.parse(classCollectiveQuery);
    optionList.value = classCollectiveQueryJson.optionList;
    activeKey.value = classCollectiveQueryJson.activeKey;
    formState.value = classCollectiveQueryJson.formState;
    tabsName.value = classCollectiveQueryJson.tabsName;
    tabsId.value = classCollectiveQueryJson.tabsId;
    // console.log(
    //   filterChangeRef.value,
    //   'filterChangeRef.value',
    //   classCollectiveQueryJson.gradeAndClass
    // );
    // setTimeout(() => {
    filterChangeRef.value.gradeAndClass = classCollectiveQueryJson.gradeAndClass;
    filterChangeRef.value.sectionList = classCollectiveQueryJson.sectionList;
    filterChangeRef.value.gradeAndClassText = classCollectiveQueryJson.gradeAndClassText;
    // }, 200);
    // nextTick(() => {
    //   filterChangeRef.value.gradeAndClass = classCollectiveQueryJson.gradeAndClass;
    //   filterChangeRef.value.sectionList = classCollectiveQueryJson.sectionList;
    //   filterChangeRef.value.gradeAndClassText = classCollectiveQueryJson.gradeAndClassText;
    // });
    if (
      !classCollectiveQuery ||
      classCollectiveQuery === null ||
      classCollectiveQuery === undefined
    ) {
      dayCreateValue.value = [
        dayjs(moment().format('YYYY-MM-DD 00:00')),
        dayjs(moment().format('YYYY-MM-DD 23:59'))
      ];
      formState.value.createValue = dayCreateValue.value;
    } else {
      if (formState.value.examineStartTime && formState.value.examineStartTime !== null) {
        dayCreateValue.value = [
          dayjs(moment().format(formState.value.examineStartTime)),
          dayjs(moment().format(formState.value.examineStopTime))
        ];
      } else {
        dayCreateValue.value = [];
      }
      formState.value.createValue = dayCreateValue.value;
      console.log('wcndlgd', formState.value.createValue);
    }
    console.log('ojbk----', formState.value);
    console.log('classCollectiveQueryJson', classCollectiveQueryJson);
    console.log('activeKey.value', activeKey.value);
    dataForm();
  }
}
import { useStore } from 'vuex';
import { dormitoryCheckRanking } from '@/api/assessment/dormitoryCollective';

const store = useStore();
const stateUser = computed(() => store.state.user.STATE_USER);
// const stateUser = ref(JSON.parse(localStorage.getItem('STATE_USER')));

const loading = ref(true);
// 下拉选项列表
const optionList = ref({
  gradeList: [],
  classList: []
});
// 表格信息
const tableData = ref([]);
// 获取表格信息
function getTabsList(parmas) {
  loading.value = true;
  getClassExamineCategory(parmas).then(res => {
    if (res.data.code === 200) {
      tableData.value = res.data.data;
      tableData.value.records.forEach((i, index) => {
        i.indexId = index + 1;
      });
      console.log(tableData.value, 'qit');
      loading.value = false;
    }
    loading.value = false;
  });
}
// 获取表格信息--综合查询
function getTabsListComplex(parmas) {
  console.log('****222*', parmas);
  parmas.data.sort = null;
  loading.value = true;
  getComplexExamineCategory(parmas)
    .then(res => {
      if (res.data.code === 200) {
        tableData.value = res.data.data;
        tableData.value.records.forEach((i, index) => {
          i.indexId = index + 1;
        });
        console.log(tableData.value, 'zonghe');
        loading.value = false;
      }
      loading.value = false;
    })
    .catch(e => {
      tableData.value = [];
      tableData.value.current = 1;
      tableData.value.size = 10;
      loading.value = false;
    });
}
let tabsName = ref('');
let tabsId = ref('');
// tabs改变回调
async function onTabsValue(e, status) {
  searchStatus.value = 0;
  let classCollectiveQuery = localStorage.getItem('classCollectiveQuery');
  if (status * 1 === 1) {
    localStorage.removeItem('classCollectiveQuery');
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
    formState.value.examineStartTime = dayCreateValue.value[0];
    formState.value.examineStopTime = dayCreateValue.value[1];
    await resetForm();
  }

  if (
    !classCollectiveQuery ||
    classCollectiveQuery === null ||
    classCollectiveQuery === undefined
  ) {
    // formState.value.examineStartTime = '';
    // formState.value.examineStopTime = '';
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
    formState.value.examineStartTime = dayCreateValue.value[0];
    formState.value.examineStopTime = dayCreateValue.value[1];
    tabsName.value = e.itemName;
    tabsId.value = e.id;
    filterChangeRef.value.gradeAndClass = [];
  } else {
    activeKey.value = JSON.parse(classCollectiveQuery).activeKey;
    tabsName.value = JSON.parse(classCollectiveQuery).tabsName;
    tabsId.value = JSON.parse(classCollectiveQuery).tabsId;
  }
  loading.value = true;
  formState.value.createValue = dayCreateValue.value;

  selectedRowKeys.value = [];
  selectedRows.value = [];

  if (e.id !== undefined) {
    onFinish(e.id);
    if (
      !classCollectiveQuery ||
      classCollectiveQuery === null ||
      classCollectiveQuery === undefined
    ) {
      activeKey.value = e.id;
      tabsName.value = e.itemName;
      tabsId.value = e.id;
    }
    rankingState.value = false;
  } else {
    onFinish('all');
    activeKey.value = 'all';
    tabsName.value = e.itemName;
    tabsId.value = e.id;
    rankingState.value = false;
  }
  console.log(tabsId.value, 'tabsId.value ');
  dataForm();

  if (
    !classCollectiveQuery ||
    classCollectiveQuery === null ||
    classCollectiveQuery === undefined
  ) {
    await resetForm();
  }
  await onSearch();
  localStorage.removeItem('classCollectiveQuery');
}

// onReset
const onReset = async () => {
  searchStatus.value = 0;
  formState.value.createValue = dayCreateValue.value;
  formState.value.examineStartTime = startTime;
  formState.value.examineStopTime = endTime;
  selectedRowKeys.value = [];
  selectedRows.value = [];
  formState.value.createValue = [
    dayjs(moment().format('YYYY-MM-DD 00:00')),
    dayjs(moment().format('YYYY-MM-DD 23:59'))
  ];
  optionList.value.classList = [];
  filterChangeRef.value.gradeAndClass = [];
  onSearch();
};

// 重置
const resetForm = () => {
  // formState.value.gradeId = undefined;
  // formState.value.classId = undefined;
  formState.value.createValue = dayCreateValue.value;
  formState.value.examineStartTime = startTime;
  formState.value.examineStopTime = endTime;

  optionList.value.classList = [];
  // onSearch();
};

// 查询 按钮
const onSearch = status => {
  // 手动点击
  if (status * 1 === 1) {
    searchStatus.value = 1;
    formState.value.current = 1;
  }
  if (activeKey.value === 'all' && rankingState.value === true) {
    console.log('lorem0');
    orderby(!rankingOrder.value);
  } else {
    console.log('lorem1');
    if (status * 1 === 1) {
      selectedRowKeys.value = [];
      selectedRows.value = [];
    }
    let obj = {
      data: formState.value,
      current: formState.value.current,
      size: formState.value.size
    };
    obj.data.classIdCondition = filterChangeRef.value.disposeChangeData();
    loading.value = true;
    console.log('走查询了lelelelllele', obj);
    if (formState.value.itemSuperiorId !== 0) {
      console.log('lorem2');
      getTabsList(obj);
    } else {
      console.log('lorem3');
      getTabsListComplex(obj);
    }
  }
};

// 时间设置
const onRangeChange = (dates, dateString) => {
  formState.value.createValue = dates;
  if (dateString.length > 0) {
    if (dateString[0].length === 10) {
      formState.value.examineStartTime = dateString[0] + ' 00:00:00';
    } else {
      formState.value.examineStartTime = dateString[0];
    }
    if (dateString[1].length === 10) {
      formState.value.examineStopTime = dateString[1] + ' 23:59:59';
    } else {
      formState.value.examineStopTime = dateString[1];
    }
  }
  console.log('时间设置回调', formState);
  console.log('时间设置回调dateString', dateString);
};
// tabs 激活标签
const activeKey = ref('');
// 表格多选
const selectedRowKeys = ref([]);
const selectedRows = ref([]);
// table 多选回调
const onSelectChange = (rowKeys, rows) => {
  selectedRowKeys.value = rowKeys;
  selectedRows.value = rows;
  console.log(selectedRowKeys.value, 'rowKeys');
};
// 指定每页条数
const pageSizeOptions = ref(['10', '20', '30', '40', '50', '100', '500', '1000']);
// 分页发生改变
const onChangePagination = value => {
  // if (formState.value.examineStartTime === '') {
  //   formState.value.examineStartTime = startTime;
  // }
  // if (formState.value.examineStopTime === '') {
  //   formState.value.examineStopTime = endTime;
  // }
  let roomId;
  if (
    formState.value.roomId &&
    formState.value.roomId !== undefined &&
    formState.value.roomId !== null
  ) {
    roomId = formState.value.roomId[formState.value.roomId.length - 1];
  } else {
    roomId = undefined;
  }
  let obj = {
    data: formState.value,
    current: tableData.value.current,
    size: tableData.value.size
  };
  formState.value.current = tableData.value.current;
  formState.value.size = tableData.value.size;

  obj.data.classIdCondition = filterChangeRef.value.disposeChangeData();
  if (localStorage.classCollectiveQuery) {
    obj.data.classIdCondition = JSON.parse(localStorage.classCollectiveQuery).classIdCondition;
  }

  if (formState.value.itemSuperiorId !== 0) {
    getTabsList(obj);
  } else {
    // 综合检查
    console.log(order.value, 'order.value');
    if (activeKey.value === 'all' && !rankingState.value) {
      // 综合检查
      obj = {
        // data: {
        //   dormitoryId: formState.value.dormitoryId, // 宿舍楼
        //   // roomId: formState.value.roomId.length
        //   //   ? formState.value.roomId[formState.value.roomId.length - 1]
        //   //   : null, // 房间名称
        //   roomId: roomId,
        //   startTime: formState.value.startTime, // 检查时间开始
        //   endTime: formState.value.endTime, // 检查时间结束
        //   roomIds: [],
        //   itemSuperiorId: formState.value.itemSuperiorId
        // },
        data: formState.value,
        current: tableData.value.current,
        size: tableData.value.size
      };
      obj.data.classIdCondition = filterChangeRef.value.disposeChangeData();
      if (localStorage.classCollectiveQuery) {
        obj.data.classIdCondition = JSON.parse(localStorage.classCollectiveQuery).classIdCondition;
      }
      // 综合检查接口
      getTabsListComplex(obj);
    } else {
      // // 排序
      // obj = {
      //   // data: {
      //   //   dormitoryId: formState.value.dormitoryId, // 宿舍楼
      //   //   // roomId: formState.value.roomId.length
      //   //   //   ? formState.value.roomId[formState.value.roomId.length - 1]
      //   //   //   : null, // 房间名称
      //   //   roomId: roomId,
      //   //   startTime: formState.value.startTime, // 检查时间开始
      //   //   endTime: formState.value.endTime, // 检查时间结束
      //   //   roomIds: [],
      //   //   itemSuperiorId: formState.value.itemSuperiorId
      //   // },
      //   data: formState.value,
      //   current: tableData.value.current,
      //   size: tableData.value.size,
      //   orders: [
      //     {
      //       column: 'scoreRank',
      //       asc: order.value
      //     }
      //   ]
      // };
      // // 排序接口
      // dormitoryCheckRanking(obj).then(res => {
      //   tableData.value = res.data.data;
      // });
      // getTabsListComplex(obj);

      orderby(!rankingOrder.value);
    }
  }
};
// 获取当前时间
let start = moment(new Date(new Date(new Date().toLocaleDateString()).getTime())).format(
  'YYYY-MM-DD HH:mm:ss'
);
let end = moment(
  new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
).format('YYYY-MM-DD HH:mm:ss');

// 查看详情
const onDeta = (record, classId, className, gradeName) => {
  saveQuery();
  let path = null;
  // let data = ref(record);
  if (formState.value.examineStartTime === '') {
    formState.value.examineStartTime = start;
  }
  if (formState.value.examineStopTime === '') {
    formState.value.examineStopTime = end;
  }
  if (activeKey.value === 'all') {
    path = '/check/classCollective/allDeta';
    router.push({
      path,
      query: {
        gradeName: gradeName,
        className: className,
        classId: classId,
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime // 检查时间结束
      }
    });
  } else {
    path = '/check/classCollective/interiorDeta';
    router.push({
      path,
      query: {
        record: JSON.stringify(record),
        activeName: tabsName.value,
        activeId: tabsId.value
      }
    });
  }
};
function saveQuery() {
  let json = {
    activeKey: activeKey.value,
    formState: formState.value,
    optionList: optionList.value,
    tabsName: tabsName.value,
    tabsId: tabsId.value,
    classIdCondition: filterChangeRef.value.disposeChangeData(),
    gradeAndClass: filterChangeRef.value.gradeAndClass,
    sectionList: filterChangeRef.value.sectionList,
    gradeAndClassText: filterChangeRef.value.gradeAndClassText
  };
  console.log('保存的时候班级集体考核', json);
  localStorage.setItem('classCollectiveQuery', JSON.stringify(json));
}
const dataColumns = reactive([
  {
    key: 'className',
    title: '学段/年级/班级',
    dataIndex: 'className',
    scopedSlots: { customRender: 'className' },
    fixed: 'left'
  },
  {
    key: 'totalMarkScore',
    title: '得/扣分',
    dataIndex: 'totalMarkScore',
    scopedSlots: { customRender: 'totalMarkScore' }
  }
]);
const dataActive = reactive({
  title: '操作',
  key: 'action',
  dataIndex: 'action',
  scopedSlots: { customRender: 'action' },
  fixed: 'right',
  width: 100
});

let columns = ref([]);
const dataForm = () => {
  if (activeKey.value === 'all' && rankingState.value === true) {
    columns.value = [
      {
        key: 'scoreRank',
        title: '排名',
        dataIndex: 'scoreRank',
        scopedSlots: { customRender: 'scoreRank' }
        // fixed: 'left'
      },
      // {
      //   key: 'gradeName',
      //   title: '年级',
      //   dataIndex: 'gradeName',
      //   scopedSlots: { customRender: 'gradeName' }
      // },
      ...dataColumns,
      dataActive
    ];
  } else if (activeKey.value !== 'all') {
    columns.value = [
      ...dataColumns,
      {
        key: 'roomVOList',
        title: '得/扣分情况',
        dataIndex: 'roomVOList',
        scopedSlots: { customRender: 'roomVOList' }
      },
      {
        key: 'examineTime',
        title: '检查时间',
        dataIndex: 'examineTime',
        scopedSlots: { customRender: 'examineTime' }
      },
      dataActive
    ];
  } else {
    columns.value = [
      // {
      //   key: 'gradeName',
      //   title: '年级',
      //   dataIndex: 'gradeName',
      //   scopedSlots: { customRender: 'gradeName' }
      // },
      ...dataColumns,
      dataActive
    ];
  }
};
// 表单查询
const formRef = ref();

// label样式
// const labelCol = reactive({
//   xs: { span: 4 },
//   sm: { span: 6 }
// });
// const wrapperCol = reactive({
//   xs: { span: 24 },
//   sm: { span: 16 }
// });
const labelCol = reactive({
  xs: { span: 8 },
  xl: { span: 8 },
  xxl: { span: 6 }
});
const wrapperCol = reactive({
  xs: { span: 24 },
  xl: { span: 24 },
  xxl: { span: 24 }
});
const onFinish = values => {
  let classCollectiveQuery = localStorage.getItem('classCollectiveQuery');
  if (values === 'all') {
    values = 0;
  }

  let parmas = {
    data: {
      itemSuperiorId: values,
      studentName: undefined,
      dormitoryId: undefined,
      roomId: undefined,
      examineStartTime: formState.value.examineStartTime,
      examineStopTime: formState.value.examineStopTime
    },
    current: 1, // 当前页
    pages: 0, // 总页数
    size: 10, // 当前条数
    total: 0 // 总条数
  };
  if (!classCollectiveQuery || classCollectiveQuery == null || classCollectiveQuery === undefined) {
    if (formState.value.examineStartTime === '') {
      formState.value.examineStartTime = startTime;
    }
    if (formState.value.examineStopTime === '') {
      formState.value.examineStopTime = endTime;
    }
    formState.value.itemSuperiorId = values;
    formState.value.current = parmas.current;
    formState.value.size = parmas.size;
    activeKey.value = values;
    if (values === 0) {
      activeKey.value = 'all';
    }
  }

  /* if (formState.value.itemSuperiorId !== 0) {
    getTabsList(parmas);
  } else {
    getTabsListComplex(parmas);
  } */
};
// 时间设置
let startTime = moment(new Date(new Date(new Date().toLocaleDateString()).getTime())).format(
  'YYYY-MM-DD HH:mm:ss'
);
let endTime = moment(
  new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
).format('YYYY-MM-DD HH:mm:ss');
console.log('Time', startTime, endTime);

const rankingState = ref(false); // 排名

const rankingOrder = ref(true);
// 查看排行
function ranking() {
  // formState.value.current = 1;
  tableData.value.current = 1;
  rankingState.value = true;
  isStudentLeadingOut.value = true;
  orderby(0);
  dataForm();
}
// 正序
function asc() {
  rankingOrder.value = false;
  orderby(true);
}
// 反序
function desc() {
  rankingOrder.value = true;
  orderby(false);
}

// 分页的时候判断是否排序
let order = ref(true);
function orderby(orders) {
  console.log(orders, 'orders');
  order.value = orders;
  tableData.value.records = [];

  if (formState.value.examineStartTime === '') {
    formState.value.examineStartTime = startTime;
  }
  if (formState.value.examineStopTime === '') {
    formState.value.examineStopTime = endTime;
  }

  let obj = [];
  if (orders === false || orders === 0) {
    formState.value.sort = 1;
    obj = {
      data: formState.value,
      current: tableData.value.current,
      size: tableData.value.size
    };
  } else {
    formState.value.sort = 0;
    obj = {
      data: formState.value,
      current: tableData.value.current,
      size: tableData.value.size
    };
  }

  getComplexExamineCategory(obj).then(res => {
    tableData.value = res.data.data;
    tableData.value.records.forEach((i, index) => {
      i.indexId = index + 1;
    });
    console.log(tableData.value, '查看排行');
    loading.value = false;
  });
}

function close() {
  rankingState.value = false;
  dataForm();
  onFinish(activeKey.value);
  onSearch();
}
// 是否选择导出学生
const isStudentLeadingOut = ref(false);
const delStateClick = computed(() => {
  let str = '';
  if (isStudentLeadingOut.value) str = 'primary';
  return str;
});
watch(selectedRowKeys, value => {
  if (value.length) {
    isStudentLeadingOut.value = true;
  } else {
    isStudentLeadingOut.value = false;
  }
});
const btnLoading = ref(false);
// 导出
const exports = debounce(function () {
  btnLoading.value = true;
  if (activeKey.value === 'all' && rankingState.value === true) {
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      let objRank = {
        // gradeId: formState.value.gradeId, // 年级id
        ids: [], // 班级id
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime, // 检查时间结束
        scoreRankAsc: !rankingOrder.value // 排序
      };
      selectedRows.value.forEach(item => {
        objRank.ids.push(item.classId);
      });
      exportCollectiveRanking(objRank).then(res => {
        let url = window.URL.createObjectURL(res.data);
        let file = document.createElement('a');
        document.body.appendChild(file);
        file.href = url;
        file.download = '导出综合排名考核数据.xls';
        file.click();
        btnLoading.value = false;
        window.URL.revokeObjectURL(url);
      });
    }
  } else if (activeKey.value === 'all') {
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      let obj = {
        ids: [],
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime // 检查时间结束
      };
      selectedRows.value.forEach(item => {
        obj.ids.push(item.classId);
      });
      exportCollectiveExamine(obj).then(res => {
        let url = window.URL.createObjectURL(res.data);
        let file = document.createElement('a');
        document.body.appendChild(file);
        file.href = url;
        btnLoading.value = false;
        file.download = '导出综合考核数据.xls';
        file.click();
        window.URL.revokeObjectURL(url);
      });
    }
  } else {
    if (selectedRows.value.length <= 0) {
      btnLoading.value = false;
      Message.warning('请至少选择一条导出的数据');
    } else {
      // 导出考核
      // 班级集体的导出excel,    exportItemExamine接口 的 examineStartTime 和 examineStopTime   加上 00:00:00 和  23:59:59
      let objClass = {
        gradeExamineBOList: selectedRows.value,
        examineStartTime: formState.value.examineStartTime, // 检查时间开始
        examineStopTime: formState.value.examineStopTime, // 检查时间结束
        itemSuperiorId: formState.value.itemSuperiorId
        // itemSuperiorName: formState.value.itemSuperiorName
      };
      /* selectedRows.value.forEach(item => {
        objClass.ids.push(item.classId);
      }); */
      console.log('****selectedRows***');
      console.log(selectedRows.value);
      exportItemExamine(objClass).then(res => {
        let url = window.URL.createObjectURL(res.data);
        let file = document.createElement('a');
        document.body.appendChild(file);
        file.href = url;
        btnLoading.value = false;
        file.download = '班级集体考核.xls';
        file.click();
        window.URL.revokeObjectURL(url);
      });
    }
  }
}, 500);
onUnmounted(() => {
  sessionStorage.removeItem('tableDate');
});
const filterChangeRef = ref(null);
</script>

<style lang="less" scoped>
.top,
.below {
  width: 100%;
  padding: 24px 0;
  background: #ffffff;
  border-radius: 4px;
}
.below {
  padding: 24px;
  min-height: 710px;
  .ranking {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e1dddd;
    padding-bottom: 16px;
    margin-bottom: 16px;
    &-text {
      font-size: 18px;
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      color: #222222;
    }
  }
  .search {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24px;
    .search-btn-right {
      width: 40%;
      display: flex;
      justify-content: flex-end;
    }
  }
  /deep/.micro-dormitory-empty-normal .micro-dormitory-empty-image {
    height: 100px;
  }
  /deep/.micro-dormitory-empty-img-simple {
    width: 100px;
    height: 80px;
  }
}
.top {
  margin-bottom: 24px;
  .search {
    display: flex;
    justify-content: flex-end;
    margin-right: 22px;
  }
}
.pagination {
  align-items: center;
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
/deep/.micro-dormitory-tabs-tab {
  font-size: 16px;
  padding: 12px 24px;
}
/deep/.micro-dormitory-select-arrow {
  top: 40%;
}
/deep/.micro-dormitory-table-content {
  min-height: 55vh;
}
</style>
